package com.jhhc.StormSurgeForecast.Calculate.util;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jhhc.RHDB.Data.Pojo.ST_RIVER_R;
import com.jhhc.RHDB.Data.entity.BdmsStatisticalData;
import com.jhhc.RHDB.RiverForecast.Calculate.entity.HY_DQ_C;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.BDMS_CALCULATESCHEME_M1;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.BDMS_FBC_TFPATH_F;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.BDMS_FBC_TFPATH_R;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Util.TimeObject;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Util.TimeUtil;
import com.jhhc.StormSurgeForecast.Calculate.BO.CenterUrl;
import com.jhhc.StormSurgeForecast.Calculate.BO.ModelConfig;
import com.jhhc.StormSurgeForecast.Calculate.DTO.JobParam;
import com.jhhc.StormSurgeForecast.Calculate.DTO.MapAppJobInfo;
import com.jhhc.StormSurgeForecast.Calculate.DTO.ModelParam;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.FBC.BDMS_FBC_OCEANMODEL_B;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author
 * 模型调用工具类
 */
public class CalUtil {

    /**
     * 获取token
     * @param modelConfig 获取token需要的参数
     * @return token
     */
    public String getToken(ModelConfig modelConfig){
        String url = modelConfig.getUrl() + "/ac/openapi/v2/tokens";
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("user", modelConfig.getUser());
        httpPost.addHeader("password", modelConfig.getPassword());
        httpPost.addHeader("orgId", modelConfig.getOrgId());
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            String token = null;
            for (Object o : jsonArray) {
                JSONObject object = (JSONObject) o;
                String clusterName = object.getString("clusterName");
                if (clusterName.contains("西安")) {
                    token = object.getString("token");
                    break;
                }
            }
            httpClient.close();
            return token;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("接口请求异常");
            return null;
        }
    }
    /**
     * 获取授权区域地址center
     * @return token
     */
    public CenterUrl getCenter(String token,ModelConfig modelConfig){
        String url = modelConfig.getUrl() + "/ac/openapi/v2/center";
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        httpGet.setConfig(requestConfig);
        httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
        httpGet.setHeader("token",token);
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray efileUrls = data.getJSONArray("efileUrls");
            JSONArray hpcUrls = data.getJSONArray("hpcUrls");
            JSONArray aiUrls = data.getJSONArray("aiUrls");
            String efileUrl = null;
            String hpcUrl = null;
            String aiUrl = null;
            for (Object o : efileUrls) {
                JSONObject object = (JSONObject) o;
                String clusterName = object.getString("enable");
                if (clusterName.contains("true")) {
                    efileUrl = object.getString("url");
                    break;
                }
            }
            for (Object o : hpcUrls) {
                JSONObject object = (JSONObject) o;
                String clusterName = object.getString("enable");
                if (clusterName.contains("true")) {
                    hpcUrl = object.getString("url");
                    break;
                }
            }
            for (Object o : aiUrls) {
                JSONObject object = (JSONObject) o;
                String clusterName = object.getString("enable");
                if (clusterName.contains("true")) {
                    aiUrl = object.getString("url");
                    break;
                }
            }
            CenterUrl centerUrl = new CenterUrl();
            centerUrl.setEfileUrl(efileUrl);
            centerUrl.setHpcUrl(hpcUrl);
            centerUrl.setAiUrl(aiUrl);
            httpClient.close();
            return centerUrl;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("接口请求异常");
            return null;
        }
    }

    /**
     * 文件上传
     * @param url 获取可用的文件上传连接
     * @param token token
     * @param file 需要上传文件的文件
     * @param path 上传到服务器的目录
     * @return 调用结果
     */
    public String fileUpload(String url,String token ,File file,String path){
        url = url + "/openapi/v2/file/upload";
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        // 设置请求头 boundary边界不可重复，重复会导致提交失败
        String boundary = "-------------------------" + UUID.randomUUID().toString();
        httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
        httpPost.addHeader("token", token);
        // 创建MultipartEntityBuilder
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // 设置字符编码
        builder.setCharset(StandardCharsets.UTF_8);
        // 模拟浏览器
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        // 设置边界
        builder.setBoundary(boundary);
        // 设置multipart/form-data流文件
        //builder.addPart("multipartFile", new FileBody(file));
        // 添加form-data参数
        builder.addTextBody("path", path);
        builder.addTextBody("cover", "cover");
        builder.addBinaryBody("file", file, ContentType.create("application/octet-stream"), file.getName());
        // 构建HttpEntity对象
        HttpEntity multipart = builder.build();
        // 设置请求体
        httpPost.setEntity(multipart);
        // 发送请求并获取响应
        try {
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            httpClient.close();
            return jsonObject.getString("code");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("上传文件请求异常");
            return null;
        }
    }
    /**
     * 下载文件，普通下载，适合小文件
     * @param url 获取可用的文件上传连接
     * @param path 要下载的文件或文件夹的地址
     * @return token
     */
    public boolean fileDownload(String url,String token,String path,String localPath){
        url = url + "/openapi/v2/file/download";
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        // 设置URI
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameter("path", path);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
            httpGet.setHeader("token",token);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            try {
                InputStream input = new ByteArrayInputStream(result.getBytes());;//获取流
                File file = new File(localPath);
                FileOutputStream outputStream = new FileOutputStream(file);
                int read;
                byte[] bytes = new byte[1024];
                while ((read = input.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                input.close();
                outputStream.close();
                httpClient.close();
            }catch (IOException e){
                e.printStackTrace();
            }
            return true;
        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
            System.out.println("接口请求异常");
            return false;
        }
    }

    /**
     * 下载文件,流式下载，下载大文件
     * @param url 获取可用的文件上传连接
     * @param path 要下载的文件或文件夹的地址
     * @return token
     */
    public boolean fileDownload1(String url,String token,String path,String localPath){
        url = url + "/openapi/v2/file/download?path=" + path;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            URL ur = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) ur.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("token",token);
            inputStream = new BufferedInputStream(connection.getInputStream());
            File file = new File(localPath);
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            //这里也很关键每次读取的大小为5M 不一次性读取完
            byte[] buffer = new byte[1024 * 1024 * 20];// 5MB
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            connection.disconnect();
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 获取文件列表
     * @param url 获取可用的文件资源连接
     * @param path 目标文件夹地址
     * @return token
     */
    public List<String> fileList(String url,String token,String path){
        url = url + "/openapi/v2/file/list";
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        // 设置URI
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameter("path", path);
            builder.setParameter("limit","100");
            builder.setParameter("order","asc");
            builder.setParameter("start","0");
            builder.setParameter("keyWord","BTFUP");
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                    .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
            httpGet.setConfig(requestConfig);
            httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
            httpGet.setHeader("token",token);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray jsonArray = data.getJSONArray("fileList");
            List<String> filePath = new ArrayList<>();
            try {
                for (Object o : jsonArray) {
                    JSONObject object = (JSONObject) o;
                    filePath.add(object.getString("path"));
                }
            }catch (NullPointerException e){
                e.printStackTrace();
                System.out.println("获取文件列表异常");
            }
            return filePath;
        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
            System.out.println("接口请求异常");
            return null;
        }
    }

    /**
     * 判断文件是否存在
     * @param url 获取可用的文件资源连接
     * @param path 目标文件地址
     * @return token
     */
    public boolean fileExist(String url,String token,String path){
        url = url + "/openapi/v2/file/exist?path=" + path;
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        // 设置URI
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
        httpPost.setHeader("token",token);
        try {
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            JSONObject data = jsonObject.getJSONObject("data");
            String exist = data.getString("exist");
            httpClient.close();
            return "true".equals(exist);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 提交作业  创建计算方案id文件夹
     * @param url 获取可用的文件上传连接
     * @param token token
     * @return 调用结果
     */
    public String createFolder(String url,String token ,String cschemePath,ModelConfig modelConfig){
        url = url + "/hpc/openapi/v2/apptemplates/BASIC/BASE/job";
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.addHeader("token", token);
        JobParam jobParam = new JobParam();
        jobParam.setStrJobManagerID(modelConfig.getStrJobManagerId());
        MapAppJobInfo mapAppJobInfo = new MapAppJobInfo();
        mapAppJobInfo.setGAP_CMD_FILE("mkdir " + cschemePath);
        mapAppJobInfo.setGAP_NODE_STRING("");
        mapAppJobInfo.setGAP_SUBMIT_TYPE("cmd");
        mapAppJobInfo.setGAP_JOB_NAME("创建方案文件夹");
        mapAppJobInfo.setGAP_WORK_DIR(cschemePath);
        mapAppJobInfo.setGAP_QUEUE(modelConfig.getQueuename());
        //河海超算配置
        mapAppJobInfo.setGAP_NPROC("15");
        mapAppJobInfo.setGAP_NNODE("8");
        mapAppJobInfo.setGAP_NGPU("");
        mapAppJobInfo.setGAP_NDCU("");
        mapAppJobInfo.setGAP_WALL_TIME("1:00:00");
        mapAppJobInfo.setGAP_EXCLUSIVE("");
        mapAppJobInfo.setGAP_APPNAME("adcprep");
        mapAppJobInfo.setGAP_STD_OUT_FILE(modelConfig.getUserpathname() + "model/log/std.out.%j");
        mapAppJobInfo.setGAP_STD_ERR_FILE(modelConfig.getUserpathname() + "model/log/std.err.%j");
        jobParam.setMapAppJobInfo(mapAppJobInfo);
        String param = JSONObject.toJSONString(jobParam);
        StringEntity entity2 = new StringEntity(param, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity2);
        try {
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            String jobId = jsonObject.getString("data");
            httpClient.close();
            return jobId;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("提交创建文件夹作业异常");
            return null;
        }
    }
    /**
     * 提交作业  复制对应模型文件夹到计算方案id文件夹下
     * @param url 获取可用的文件上传连接
     * @param token token
     * @return 调用结果
     */
    public String copyFolder(String url,String token,String cschemePath,
                             ModelConfig modelConfig,String modelPtah){
        url = url + "/hpc/openapi/v2/apptemplates/BASIC/BASE/job";
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.addHeader("token", token);
        JobParam jobParam = new JobParam();
        jobParam.setStrJobManagerID(modelConfig.getStrJobManagerId());
        MapAppJobInfo mapAppJobInfo = new MapAppJobInfo();
        mapAppJobInfo.setGAP_CMD_FILE("scp -r " + modelPtah + " " + cschemePath);
        mapAppJobInfo.setGAP_NODE_STRING("");
        mapAppJobInfo.setGAP_SUBMIT_TYPE("cmd");
        mapAppJobInfo.setGAP_JOB_NAME("复制模型文件");
        mapAppJobInfo.setGAP_WORK_DIR(cschemePath);
        mapAppJobInfo.setGAP_QUEUE(modelConfig.getQueuename());
        //河海超算配置
        mapAppJobInfo.setGAP_NPROC("15");
        mapAppJobInfo.setGAP_NNODE("8");
        mapAppJobInfo.setGAP_NGPU("");
        mapAppJobInfo.setGAP_NDCU("");
        mapAppJobInfo.setGAP_WALL_TIME("1:00:00");
        mapAppJobInfo.setGAP_EXCLUSIVE("");
        mapAppJobInfo.setGAP_APPNAME("adcprep");
        mapAppJobInfo.setGAP_STD_OUT_FILE(modelConfig.getUserpathname() + "model/log/std.out.%j");
        mapAppJobInfo.setGAP_STD_ERR_FILE(modelConfig.getUserpathname() + "model/log/std.err.%j");
        jobParam.setMapAppJobInfo(mapAppJobInfo);
        String param = JSONObject.toJSONString(jobParam);
        StringEntity entity2 = new StringEntity(param, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity2);
        try {
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            String jobId = jsonObject.getString("data");
            httpClient.close();
            return jobId;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("提交复制模型文件夹作业异常");
            return null;
        }
    }

    /**
     * 提交作业  模型计算
     * @param url 获取可用的文件上传连接
     * @param token token
     * @return 调用结果
     */
    public String modelCalculate(String url,String token, ModelConfig modelConfig,String workPath){
        url = url + "/hpc/openapi/v2/apptemplates/BASIC/BASE/job";
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.addHeader("token", token);
        JobParam jobParam = new JobParam();
        jobParam.setStrJobManagerID(modelConfig.getStrJobManagerId());
        MapAppJobInfo mapAppJobInfo = new MapAppJobInfo();
        mapAppJobInfo.setGAP_CMD_FILE("sh sub.sh");
        mapAppJobInfo.setGAP_NODE_STRING("");
        mapAppJobInfo.setGAP_SUBMIT_TYPE("cmd");
        mapAppJobInfo.setGAP_JOB_NAME("模型计算");
        mapAppJobInfo.setGAP_WORK_DIR(workPath);
        mapAppJobInfo.setGAP_QUEUE(modelConfig.getQueuename());
        //河海
        mapAppJobInfo.setGAP_NPROC("900");
        mapAppJobInfo.setGAP_NNODE("15");
        //mapAppJobInfo.setGAP_PPN("");
        mapAppJobInfo.setGAP_NGPU("");
        mapAppJobInfo.setGAP_NDCU("");
        mapAppJobInfo.setGAP_WALL_TIME("1:00:00");
        mapAppJobInfo.setGAP_EXCLUSIVE("1");
        mapAppJobInfo.setGAP_APPNAME("adcprep");
       // mapAppJobInfo.setGAP_MULTI_SUB("");
        mapAppJobInfo.setGAP_STD_OUT_FILE(modelConfig.getUserpathname() + "model/log/std.out.%j");
        mapAppJobInfo.setGAP_STD_ERR_FILE(modelConfig.getUserpathname() + "model/log/std.err.%j");
        jobParam.setMapAppJobInfo(mapAppJobInfo);
        String param = JSONObject.toJSONString(jobParam);
        StringEntity entity2 = new StringEntity(param, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity2);
        try {
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            String jobId = jsonObject.getString("data");
            httpClient.close();
            return jobId;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("提交模型计算作业异常");
            return null;
        }
    }
    /**
     * 提交作业  模型计算智能校正
     * @param url 获取可用的文件上传连接
     * @param token token
     * @return 调用结果
     */
    public String modelCalculatexz(String url,String token, ModelConfig modelConfig,String workPath){
        url = url + "/hpc/openapi/v2/apptemplates/BASIC/BASE/job";
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.addHeader("token", token);
        JobParam jobParam = new JobParam();
        jobParam.setStrJobManagerID(modelConfig.getStrJobManagerId());
        MapAppJobInfo mapAppJobInfo = new MapAppJobInfo();
        mapAppJobInfo.setGAP_CMD_FILE("sh tide_pre.sh");
        mapAppJobInfo.setGAP_NODE_STRING("");
        mapAppJobInfo.setGAP_SUBMIT_TYPE("cmd");
        mapAppJobInfo.setGAP_JOB_NAME("模型计算");
        mapAppJobInfo.setGAP_WORK_DIR(workPath);
        mapAppJobInfo.setGAP_QUEUE(modelConfig.getQueuename());
        //河海
        mapAppJobInfo.setGAP_NPROC("900");
        mapAppJobInfo.setGAP_NNODE("15");
        //mapAppJobInfo.setGAP_PPN("");
        mapAppJobInfo.setGAP_NGPU("");
        mapAppJobInfo.setGAP_NDCU("");
        mapAppJobInfo.setGAP_WALL_TIME("1:00:00");
        mapAppJobInfo.setGAP_EXCLUSIVE("1");
        mapAppJobInfo.setGAP_APPNAME("adcprep");
        // mapAppJobInfo.setGAP_MULTI_SUB("");
        mapAppJobInfo.setGAP_STD_OUT_FILE(modelConfig.getUserpathname() + "model/log/std.out.%j");
        mapAppJobInfo.setGAP_STD_ERR_FILE(modelConfig.getUserpathname() + "model/log/std.err.%j");
        jobParam.setMapAppJobInfo(mapAppJobInfo);
        String param = JSONObject.toJSONString(jobParam);
        StringEntity entity2 = new StringEntity(param, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity2);
        try {
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            String jobId = jsonObject.getString("data");
            httpClient.close();
            return jobId;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("提交模型计算作业异常");
            return null;
        }
    }
    /**
     * 提交作业  模型计算 智能预报
     * @param url 获取可用的文件上传连接
     * @param token token
     * @return 调用结果
     */
    public String modelCalculatecw(String url,String token, ModelConfig modelConfig,String workPath){
        url = url + "/hpc/openapi/v2/apptemplates/BASIC/BASE/job";
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.addHeader("token", token);
        JobParam jobParam = new JobParam();
        jobParam.setStrJobManagerID(modelConfig.getStrJobManagerId());
        MapAppJobInfo mapAppJobInfo = new MapAppJobInfo();
        mapAppJobInfo.setGAP_CMD_FILE("sh storm_tide_pre.sh");
        mapAppJobInfo.setGAP_NODE_STRING("");
        mapAppJobInfo.setGAP_SUBMIT_TYPE("cmd");
        mapAppJobInfo.setGAP_JOB_NAME("模型计算");
        mapAppJobInfo.setGAP_WORK_DIR(workPath);
        mapAppJobInfo.setGAP_QUEUE(modelConfig.getQueuename());
        //河海
        mapAppJobInfo.setGAP_NPROC("900");
        mapAppJobInfo.setGAP_NNODE("15");
        //mapAppJobInfo.setGAP_PPN("");
        mapAppJobInfo.setGAP_NGPU("");
        mapAppJobInfo.setGAP_NDCU("");
        mapAppJobInfo.setGAP_WALL_TIME("1:00:00");
        mapAppJobInfo.setGAP_EXCLUSIVE("1");
        mapAppJobInfo.setGAP_APPNAME("adcprep");
        // mapAppJobInfo.setGAP_MULTI_SUB("");
        mapAppJobInfo.setGAP_STD_OUT_FILE(modelConfig.getUserpathname() + "model/log/std.out.%j");
        mapAppJobInfo.setGAP_STD_ERR_FILE(modelConfig.getUserpathname() + "model/log/std.err.%j");
        jobParam.setMapAppJobInfo(mapAppJobInfo);
        String param = JSONObject.toJSONString(jobParam);
        StringEntity entity2 = new StringEntity(param, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity2);
        try {
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            String jobId = jsonObject.getString("data");
            httpClient.close();
            return jobId;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("提交模型计算作业异常");
            return null;
        }
    }

    /**
     * 查询作业详细信息
     * @param url 获取可用的文件上传连接
     * @param jobId 作业id
     * @param token token
     */
    public String queryJobs(String url,String token,String jobId){
        url = url + "/hpc/openapi/v2/jobs/" + jobId;
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        // 设置URI
        try {
//            URIBuilder builder = new URIBuilder(url);
//            builder.setParameter("jobId", jobId);
//            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                    .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
            httpGet.setConfig(requestConfig);
            httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
            httpGet.setHeader("token",token);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            System.out.println(jsonObject);
            JSONObject data = jsonObject.getJSONObject("data");
            try {
                System.out.println(data.toString());
            }catch (NullPointerException e){
                e.printStackTrace();
                httpClient.close();
                return null;
            }
            String status = data.getString("jobStatus");
            httpClient.close();
            return status;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("接口请求异常");
            return null;
        }

    }

    /**
     * 创建nhup1.txt文件
     * @param forecastTime 实测路径时间点
     * @param localPath 计算方案id
     * @param endTime 结束时间，预报路径最后一个时间点
     * @return 成功或者失败
     */
    public File createNhup1File(String forecastTime,String localPath,String endTime,
                                  String modelPar,boolean isArea,BDMS_FBC_OCEANMODEL_B bdmsFbcOceanmodelB){
        try {
            File pathFile = ModelUtil.createFile(localPath,"nhup1.txt");
            FileOutputStream fos = new FileOutputStream(pathFile,true);
            byte[] sBytes;
            StringBuilder value = new StringBuilder();
            TimeUtil timeUtil = new TimeUtil();
            TimeObject timeObject = timeUtil.currentTimes1(forecastTime);
            TimeObject timeObject1 = timeUtil.currentTimes1(endTime);
            switch (bdmsFbcOceanmodelB.getModelid()){
                case "HHUCCHAOSUANNS"://南海超算模型
                case "HoHaiSouthSeaZs"://南海模型
                case "HoHaiEastSeaZS"://东海模型
                    value.append("tfpath.dat").append("\r\n").append("N").append("\r\n").append(timeObject.getYear()).
                            append(",").append(timeObject.getMonth()).append(",").append(timeObject.getDay()).append(",").
                            append(timeObject.getHour()).append("\r\n").append(timeObject1.getMonth()).append(",").
                            append(timeObject1.getDay()).append(",").append(timeObject1.getHour()).append("\r\n").append(modelPar).
                            append("\r\n").append("2").append("\r\n").append(bdmsFbcOceanmodelB.getInterval()).append("\r\n").
                            append(bdmsFbcOceanmodelB.getIntervalArea()).append("\r\n").append(isArea?"Y":"N");
                    break;
                case "HHUCCHAOSUAN":
                    value.append("tfpath.dat").append("\r\n").append("N").append("\r\n").append(timeObject.getYear()).
                            append(",").append(timeObject.getMonth()).append(",").append(timeObject.getDay()).append(",").
                            append(timeObject.getHour()).append("\r\n").append(timeObject1.getMonth()).append(",").
                            append(timeObject1.getDay()).append(",").append(timeObject1.getHour()).append("\r\n").append(modelPar).
                            append("\r\n").append(isArea ? "Y":"N").append("\r\n").append(1800);
                    break;
                case "JSCoastTide":
                    value.append("tfpath.dat").append("\r\n").append("A").append("\r\n").append(timeObject.getYear()).
                            append(",").append(timeObject.getMonth()).append(",").append(timeObject.getDay()).append(",").
                            append(timeObject.getHour()).append("\r\n").append(timeObject1.getMonth()).append(",").
                            append(timeObject1.getDay()).append(",").append(timeObject1.getHour()).append("\r\n").append(modelPar).
                            append("\r\n").append(isArea ? "Y":"N").append("\r\n").append(1800).append("\r\n");
                case "JSCoastSurge":
                    value.append("tfpath.dat").append("\r\n").append("N").append("\r\n").append(timeObject.getYear()).
                            append(",").append(timeObject.getMonth()).append(",").append(timeObject.getDay()).append(",").
                            append(timeObject.getHour()).append("\r\n").append(timeObject1.getMonth()).append(",").
                            append(timeObject1.getDay()).append(",").append(timeObject1.getHour()).append("\r\n").append(modelPar).
                            append("\r\n").append(isArea ? "Y":"N").append("\r\n");
                case "JSChangJiang":
                    value.append("tfpath.dat").append("\r\n").append("N").append("\r\n").append(timeObject.getYear()).
                            append(",").append(timeObject.getMonth()).append(",").append(timeObject.getDay()).append(",").
                            append(timeObject.getHour()).append(",").append("\r\n").append(timeObject1.getMonth()).append(",").
                            append(timeObject1.getDay()).append(",").append(timeObject1.getHour()).append("\r\n").append(modelPar).
                            append("\r\n").append(isArea ? "Y":"N").append("\r\n").append(1800).append("\r\n");
                    break;
                default:
                    break;
            }
            sBytes = value.toString().getBytes();
            fos.write(sBytes);
            fos.flush();
            fos.close();
            return pathFile;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("创建nhup1.txt文件异常");
            return null;
        }
    }
    /**
     * 创建tfpath文件 正常模式
     * @param bdmsFbcTfpathRs 实测路径
     * @param bdmsFbcTfpathFs 预报路径
     * @return 创建是否成功
     */
    public File createTfpathFile(List<BDMS_FBC_TFPATH_R> bdmsFbcTfpathRs,
                                 List<BDMS_FBC_TFPATH_F> bdmsFbcTfpathFs, String localPath,
                                 String time){
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            TimeUtil timeUtil = new TimeUtil();
            File pathFile = ModelUtil.createFile(localPath,"tfpath.dat");
            FileOutputStream fos = new FileOutputStream(pathFile,true);
            byte[] sBytes;
            TimeObject timeObject;
            StringBuilder value = new StringBuilder();
            for (BDMS_FBC_TFPATH_R tfpathR : bdmsFbcTfpathRs) {
                timeObject = timeUtil.currentTimes1(tfpathR.getYmdhm());
                value.append(timeObject.getYear()).append(" ").append(timeObject.getMonth()).append(" ").
                        append(timeObject.getDay()).append(" ").append(timeObject.getHour()).append(" ").
                        append(tfpathR.getLttd()).append(" ").append(tfpathR.getLgtd()).append(" ").
                        append(tfpathR.getPressure()).append(" ").append(tfpathR.getMaxspeed()).append("\r\n");
            }
            for (BDMS_FBC_TFPATH_F tfpathF : bdmsFbcTfpathFs) {
                if (format.parse(tfpathF.getForecasttm()).compareTo(format.parse(time)) > 0) {
                    timeObject = timeUtil.currentTimes1(tfpathF.getForecasttm());
                    value.append(timeObject.getYear()).append(" ").append(timeObject.getMonth()).append(" ").
                            append(timeObject.getDay()).append(" ").append(timeObject.getHour()).append(" ").
                            append(tfpathF.getLttd()).append(" ").append(tfpathF.getLgtd()).append(" ").
                            append(tfpathF.getPressure()).append(" ").append(tfpathF.getMaxspeed()).append("\r\n");
                }
            }
            sBytes = value.toString().getBytes();
            fos.write(sBytes);
            fos.flush();
            fos.close();
            return pathFile;
        } catch (IOException | ParseException e) {
            e.printStackTrace();
            System.out.println("创建tfpath.dat文件异常");
            return null;
        }
    }
    /**
     * 创建tfpath文件  后报模式
     * @param bdmsFbcTfpathRs 实测路径
     * @return 创建是否成功
     */
    public File createTfpathFileH(List<BDMS_FBC_TFPATH_R> bdmsFbcTfpathRs, String localPath){
        try {

            TimeUtil timeUtil = new TimeUtil();
            File pathFile = ModelUtil.createFile(localPath,"tfpath.dat");
            FileOutputStream fos = new FileOutputStream(pathFile,true);
            byte[] sBytes;
            TimeObject timeObject;
            StringBuilder value = new StringBuilder();
            for (BDMS_FBC_TFPATH_R tfpathR : bdmsFbcTfpathRs) {
                timeObject = timeUtil.currentTimes1(tfpathR.getYmdhm());
                value.append(timeObject.getYear()).append(" ").append(timeObject.getMonth()).append(" ").
                        append(timeObject.getDay()).append(" ").append(timeObject.getHour()).append(" ").
                        append(tfpathR.getLttd()).append(" ").append(tfpathR.getLgtd()).append(" ").
                        append(tfpathR.getPressure()).append(" ").append(tfpathR.getMaxspeed()).append("\r\n");
            }
            sBytes = value.toString().getBytes();
            fos.write(sBytes);
            fos.flush();
            fos.close();
            return pathFile;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("创建tfpath.dat文件异常");
            return null;
        }
    }
    /**
     * 创建discbase文件
     * @param bdmsStatisticalData 实测路径
     * @param localPath 本地路径
     * @param nhupStart1 文件开始时间
     * @return 创建是否成功
     */
    public File creatediscbase(List<BdmsStatisticalData> bdmsStatisticalData,String localPath,
                               String nhupStart1){
        try {
            List<BdmsStatisticalData> xi = bdmsStatisticalData.stream().filter
                    (x -> "8003".equals(x.getDataId())).collect(Collectors.toList());
            List<BdmsStatisticalData> dong = bdmsStatisticalData.stream().filter
                    (x -> "8002".equals(x.getDataId())).collect(Collectors.toList());
            List<BdmsStatisticalData> bei = bdmsStatisticalData.stream().filter
                    (x -> "8001".equals(x.getDataId())).collect(Collectors.toList());
            TimeUtil timeUtil = new TimeUtil();
            File pathFile = ModelUtil.createFile(localPath,"discbase.dat");
            FileOutputStream fos = new FileOutputStream(pathFile,true);
            byte[] sBytes;
            StringBuilder value = new StringBuilder();
            value.append("时间\t西江\t东江\t北江").append("\r\n");
            TimeObject timeObject = timeUtil.currentTimes1(nhupStart1);
            String year = timeObject.getYear();
            String time;
            for (int i = 0; i < xi.size(); i++) {
                TimeObject timeObject1 = timeUtil.currentTimes1(xi.get(i).getDataTm());
                time = year + "-" + timeObject1.getMonth() + "-" + timeObject1.getDay() + " "
                        + timeObject1.getHour() + ":00:00";
                for (int j = 0; j < 24; j++) {
                    TimeObject timeObject2 = timeUtil.currentTimes1(time);
                    value.append(timeObject2.getYear()).append("\t").append(timeObject2.getMonth()).append("\t").
                            append(timeObject2.getDay()).append("\t").append(j).append("\t").
                            append(xi.get(i).getStatisticalValue()).append("\t").
                            append(dong.get(i).getStatisticalValue()).append("\t").
                            append(bei.get(i).getStatisticalValue()).append("\r\n");
                    time = timeUtil.dateAddHour(time,1);
                }
            }
            sBytes = value.toString().getBytes();
            fos.write(sBytes);
            fos.flush();
            fos.close();
            return pathFile;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("创建tfpath.dat文件异常");
            return null;
        }
    }
    /**
     * 创建disbase.dat文件,有实测流量
     * @return 创建是否成功
     */
    public File createDisbase(List<ST_RIVER_R> stRiverRs, String localPath){
        try {
            TimeUtil timeUtil = new TimeUtil();
            File pathFile = ModelUtil.createFile(localPath,"discbase.dat");
            FileOutputStream fos = new FileOutputStream(pathFile,true);
            byte[] sBytes;
            StringBuilder value = new StringBuilder();
            for (ST_RIVER_R riverR : stRiverRs) {
                TimeObject timeObject = timeUtil.currentTimes1(riverR.getTm());
                value.append(timeObject.getYear()).append(" ").append(timeObject.getMonth()).append(" ").
                        append(timeObject.getDay()).append(" ").append(timeObject.getHour()).append(" ").
                        append(riverR.getQ()).append("\r\n");
            }
            sBytes = value.toString().getBytes();
            fos.write(sBytes);
            fos.flush();
            fos.close();
            return pathFile;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("创建创建disbase.dat文件异常");
            return null;
        }
    }
    /**
     * 创建disbase.dat文件,无实测流量
     * @return 创建是否成功
     */
    public File createDisbaseA(List<HY_DQ_C> hyDqCs, String localPath,String startTime){
        try {
            TimeUtil timeUtil = new TimeUtil();
            File pathFile = ModelUtil.createFile(localPath,"disbase.dat");
            FileOutputStream fos = new FileOutputStream(pathFile,true);
            byte[] sBytes;
            StringBuilder value = new StringBuilder();
            for (HY_DQ_C hyDqC : hyDqCs) {
                TimeObject timeObject = timeUtil.currentTimes1(startTime);
                value.append(timeObject.getYear()).append(" ").append(timeObject.getMonth()).append(" ").
                        append(timeObject.getDay()).append(" ").append(timeObject.getHour()).append(" ").
                        append(hyDqC.getAvq()).append("\r\n");
                startTime = timeUtil.dateAddHour(startTime,1);
            }
            sBytes = value.toString().getBytes();
            fos.write(sBytes);
            fos.flush();
            fos.close();
            return pathFile;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("创建创建disbase.dat文件异常");
            return null;
        }
    }



    public BDMS_CALCULATESCHEME_M1 insertProject(ModelParam param, String cschemeId,
                                                 BDMS_FBC_OCEANMODEL_B bdmsFbcOceanmodelB,
                                                 String endTime,String jobId){
        //方案入库
        BDMS_CALCULATESCHEME_M1 bdmsCalculateschemeM1 = new BDMS_CALCULATESCHEME_M1();
        TimeUtil timeUtil = new TimeUtil();
        bdmsCalculateschemeM1.setPid(Integer.valueOf(param.getProjectId()));
        bdmsCalculateschemeM1.setCschemeid(cschemeId);
        bdmsCalculateschemeM1.setUserid(param.getUserId());
        bdmsCalculateschemeM1.setFschemeid(param.getTyphoonDepart());
        if (bdmsFbcOceanmodelB.getInterval() != null) {
            bdmsCalculateschemeM1.setCalinterval(bdmsFbcOceanmodelB.getInterval());
        }
        bdmsCalculateschemeM1.setDtmforecast(param.getForecastTime());
        bdmsCalculateschemeM1.setDtmend(endTime);
        bdmsCalculateschemeM1.setDtmcalculate(timeUtil.currentTime());
        bdmsCalculateschemeM1.setMdid(bdmsFbcOceanmodelB.getModelid());
        bdmsCalculateschemeM1.setParams(param.getTfid() + "," +
                param.getTyphoonDepart() + "," + param.getModelPar());
        bdmsCalculateschemeM1.setCalinfo("");
        bdmsCalculateschemeM1.setParschemeid(String.valueOf(0));
        bdmsCalculateschemeM1.setFlag("n");
        bdmsCalculateschemeM1.setState("1");
        bdmsCalculateschemeM1.setCschemenm("0");
        bdmsCalculateschemeM1.setIsarea(param.isArea() ? "1":"0");
        bdmsCalculateschemeM1.setIsgen(0);
        return bdmsCalculateschemeM1;
    }

}
